package com.masasdani.paypal.controller;

import com.google.gson.JsonObject;
import com.masasdani.paypal.config.PaypalPaymentIntent;
import com.masasdani.paypal.config.PaypalPaymentMethod;
import com.masasdani.paypal.service.PaymentService;
import com.masasdani.paypal.util.URLUtils;
import com.paypal.api.payments.Links;
import com.paypal.api.payments.Payment;
import com.paypal.base.rest.PayPalRESTException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Iterator;

@Controller
@RequestMapping("/")
public class PaymentController {
	
	public static final String PAYPAL_SUCCESS_URL = "pay/success";
	public static final String PAYPAL_CANCEL_URL = "pay/cancel";
	
	private Logger log = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private PaymentService paymentService;
	
	@RequestMapping(method = RequestMethod.GET)
	public String index(){
		return "index";
	}


	@ResponseBody
	@RequestMapping(value = "restPay",method = RequestMethod.POST)
	public Object testApi(HttpServletRequest request){
		String cancelUrl = URLUtils.getBaseURl(request) + "/" + PAYPAL_CANCEL_URL;
		String successUrl = URLUtils.getBaseURl(request) + "/" + PAYPAL_SUCCESS_URL;
		try {
			Payment payment = paymentService.createPayment(
					14.00,
					"USD",
					PaypalPaymentMethod.paypal,
					PaypalPaymentIntent.sale,
					"payment description",
					cancelUrl,
					successUrl);
			JsonObject jsonObject = new JsonObject();
			jsonObject.addProperty("paymentID",payment.getId());
			return jsonObject;
		} catch (PayPalRESTException e) {
			log.error(e.getMessage());
			e.printStackTrace();
			return "redirect:/";
		}
	}

	@RequestMapping(method = RequestMethod.POST, value = "pay")
	public String pay(HttpServletRequest request){
		String cancelUrl = URLUtils.getBaseURl(request) + "/" + PAYPAL_CANCEL_URL;
		String successUrl = URLUtils.getBaseURl(request) + "/" + PAYPAL_SUCCESS_URL;
		try {
			Payment payment = paymentService.createPayment(
					4.00, 
					"USD", 
					PaypalPaymentMethod.paypal, 
					PaypalPaymentIntent.sale,
					"payment description", 
					cancelUrl, 
					successUrl);
			Iterator links = payment.getLinks().iterator();
			while (links.hasNext()) {
				Links link = (Links) links.next();
				if (link.getRel().equalsIgnoreCase("approval_url")) {
					// REDIRECT USER TO link.getHref()
					return "redirect:" + link.getHref();
				}
			}
		} catch (PayPalRESTException e) {
			log.error(e.getMessage());
		}
		return "redirect:/";
	}

	@RequestMapping(method = RequestMethod.GET, value = PAYPAL_CANCEL_URL)
	public String cancelPay(){
		return "cancel";
	}

	@RequestMapping(method = RequestMethod.GET, value = PAYPAL_SUCCESS_URL)
	public String successPay(@RequestParam("paymentId") String paymentId, @RequestParam("PayerID") String payerId){
		try {
			Payment payment = paymentService.executePayment(paymentId, payerId);
			if(payment.getState().equals("approved")){
				return "success";
			}
		} catch (PayPalRESTException e) {
			log.error(e.getMessage());
		}
		return "redirect:/";
	}

	@ResponseBody
	@RequestMapping(method = RequestMethod.POST, value = PAYPAL_SUCCESS_URL)
	public Object successPayPOST(@RequestParam("paymentID") String paymentId, @RequestParam("payerID") String payerId){
		JsonObject jsonObject = new JsonObject();
		try {
			Payment payment = paymentService.executePayment(paymentId, payerId);
			if(payment.getState().equals("approved")){
				jsonObject.addProperty("result",true);
				jsonObject.addProperty("msg","支付成功");
			}else {
				log.error("ERROR : {}",payment);
				jsonObject.addProperty("result",true);
				jsonObject.addProperty("msg","支付失败");
			}
			return jsonObject;
		} catch (PayPalRESTException e) {
			e.printStackTrace();
			jsonObject.addProperty("result",true);
			jsonObject.addProperty("msg","支付失败");
			return jsonObject;
		}
	}
	
}
